package com.zzyl.intercept;

import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstant;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.UserVo;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @FileName UserTokenInterceptor
 * @Description
 * @Author Sword
 * @date 2025-10-10
 **/

@Slf4j
@Component
public class UserTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截请求");

        //判断当前请求是否为Method方法
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //获取请求头中的token
        String token = request.getHeader(Constants.USER_TOKEN);

        //判断token是否为空
        if (StringUtils.isEmpty(token)) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }

        //解析token
        Claims claims = JwtUtil.parseJWT(
                jwtTokenManagerProperties.getBase64EncodedSecretKey(),
                token
        );

        //获取currentUser Json字符串
        String currentUser = String.valueOf(claims.get("currentUser"));

        if (ObjectUtil.isEmpty(currentUser)) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }

        //将currentUser Json字符串转为UserVo
        UserVo userVo = JSONUtil.toBean(currentUser, UserVo.class);

        //获取redis中当前用户权限路径
        String urlStr = redisTemplate.opsForValue().get(CacheConstant.PUBLIC_ACCESS_URLS + userVo.getId());

        //将urlStr转为List
        List<String> urlList = new ArrayList<>();
        if (StringUtils.isNotEmpty(urlStr)) {
            urlList = JSONUtil.toList(urlStr, String.class);
        }

        //判断当前请求的url是否在urlList中
        String targetUrl = request.getMethod() + request.getRequestURI();

        for (String url : urlList) {
            if (antPathMatcher.match(url, targetUrl)) {
                //存储threadLocal中
                UserThreadLocal.setSubject(currentUser);
                return true;
            }
        }

        throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.removeSubject();
    }
}
